<script lang="ts">
import { useLocale } from '~/modules/locale';
import { useOnGamePM } from '~/pages/play/self/helpers';
import { getCookieValue } from '~/utils';
import DetailSkeleton from './DetailSkeleton.vue';
</script>

<script setup lang="ts">
const props = defineProps<{
  gameCode: string;
  orderNo: string;
}>();
const emits = defineEmits<{
  close: [];
}>();
const router = useRouter();
const appStore = useAppStore();
const { locale } = useLocale();
const isIFrameLoaded = ref(false);
const url = computed(() => {
  let url: URL;

  if (import.meta.env.DEV) {
    const gamePort = location.href.match(/url=http.+(\d{4})(%2F)?$/)?.[1] ?? 0;
    url = new URL(`http://${location.hostname}:${gamePort}/`);
  }
  else {
    const origin = appStore.handshake?.domain.game.replace(/\/$/, '');

    if (!origin)
      return '';

    url = new URL(`${origin}/${props.gameCode}/`);
  }

  url.searchParams.set('token', getCookieValue('token'));
  url.searchParams.set('locale', locale.value);
  url.searchParams.set('view', 'order-detail');
  url.searchParams.set('orderNo', props.orderNo);
  url.searchParams.set('t', Date.now().toString());

  return url.toString();
});

useOnGamePM('shareGameRecord', (data) => {
  const isValid = data.gameCode && data.orderNo;
  isValid && globalPopups.orderShare.open(data);
});
useOnGamePM('toPlay', (data) => {
  const isValid = data.code;

  if (isValid) {
    router.push(`/play/${data.code}`);
    emits('close');
  }
});
useOnGamePM('loaded', () => {
  setTimeout(() => isIFrameLoaded.value = true, 500);
});
</script>

<template>
  <div class="relative overflow-hidden bg-sys-layer-d shadow-lg">
    <!-- 这个叉用于遮挡住iframe中的叉 -->
    <div
      class="absolute right-[9px] top-[11px] z-2 size-8 flex cursor-pointer items-center justify-center"
      @click="emits('close')"
    >
      <i v-if="!isIFrameLoaded" class="i-ri:close-line text-6 text-sys-text-body" />
    </div>

    <iframe v-if="url" class="block size-full border-none" :class="{ '!h-0': !isIFrameLoaded }" :src="url" />
    <DetailSkeleton v-if="!isIFrameLoaded && url" class="m-5 mt-12" />
  </div>
</template>
